import router from '@/router'
import { useUserStore } from '@/store/user'

// 退出登陆后可以访问的路由
const whiteList = ['/login', '/profile', '/401', '/404', '/']

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  const isLoginCode = await userStore.checkLoginFn()

  if (whiteList.includes(to.path)) {
    if (!isLoginCode && to.path === '/login') {
      return next('/')
    }
    next()
  } else {
    // 获取router中所有的路由
    const allRouter = router.getRoutes()

    const routeIndex = allRouter.findIndex((item) => item.path == to.path)

    // 在路由表中 且 为登陆状态
    if (routeIndex != -1 && !isLoginCode) {
      next()
    }

    // 在路由表中 且 不为登陆状态
    if (routeIndex != -1 && isLoginCode) {
      next('/401')
    }

    // 不在路由表中
    if (routeIndex == -1) {
      next('/404')
    }
  }
})
